#include "touch.h"

uint16_t TOUCH_W = 0;
uint16_t TOUCH_H = 0;

int32_t touchFd = 0;
bool isTouchFdAvailable = false;

bool Touch_Init() {
    touchFd = open(DEV_TOUCH, O_RDONLY);
    if (touchFd < 0) {
        isTouchFdAvailable = false;
        return isTouchFdAvailable;
    }

    TOUCH_W = 1024;
    TOUCH_H = 600;

    isTouchFdAvailable = true;
    return isTouchFdAvailable;
}

void Touch_Free() {
    if (isTouchFdAvailable) {
        close(touchFd);
        isTouchFdAvailable = false;
    }
}

bool Touch_CanRead() {
    return isTouchFdAvailable;
}

int32_t Touch_ReadEvent(struct input_event *ev) {
    return read(touchFd, ev, sizeof(struct input_event));
}

TouchEvent Touch_GetXY() {
    TouchEvent touch = {{0, 0}, {0, 0}, 0};
    if (!Touch_CanRead()) {
        return touch;
    }

    int16_t tempX, tempY, x1, x2, y1, y2;
    struct input_event ev;
    while (true) {
        int32_t ret = Touch_ReadEvent(&ev);
        if (ret < 0) {
            break;
        }

        if (ev.type == EV_ABS) {
            if (ev.code == ABS_X) {
                tempX = ev.value;
            } else if (ev.code == ABS_Y) {
                tempY = ev.value;
            }
        } else if (ev.type == EV_KEY && ev.code == BTN_TOUCH) {
            if (ev.value == 1) {
                x1 = 1.0 * tempX / TOUCH_W * SCREEN_W;
                y1 = 1.0 * tempY / TOUCH_H * SCREEN_H;
            } else if (ev.value == 0) {
                x2 = 1.0 * tempX / TOUCH_W * SCREEN_W;
                y2 = 1.0 * tempY / TOUCH_H * SCREEN_H;
                break;
            }
        }
    }

    touch.start.x = x1;
    touch.start.y = y1;
    touch.end.x = x2;
    touch.end.y = y2;
    touch.gesture = UNKNOWN;

    int16_t dx = x2 - x1, dy = y2 - y1;
    if (x1 * x1 + dy * dy >= SLIDE_THRESHOLD * SLIDE_THRESHOLD) {
        int16_t x0 = abs(dx);
        int16_t y0 = abs(dy);
        if (dy < 0 && y0 > x0) {  //  上划
            touch.gesture = BTT;
        } else if (dy > 0 && y0 > x0) {  // 下划
            touch.gesture = TTB;
        } else if (dx < 0 && y0 < x0) {  // 左划
            touch.gesture = RTL;
        } else if (dx > 0 && y0 < x0) {  // 右划
            touch.gesture = LTR;
        } else {
            touch.gesture = CLICK;
        }
    }

    return touch;
}
